<?php
/*
   [Wtming Project] (C) 2009-2010 StartFeel Inc.
   $Id: image.php 001 2009-05-09 13:57:13Z tomhu $
 */

include_once(S_ROOT.'./site/libs/func_util.php');
include_once(S_ROOT.'./site/libs/func_model.php');
include_once(S_ROOT.'./source/function_bbcode.php');

if(!defined('IN_UCHOME')) {
    exit('Access Denied');
}

$type = empty($_GET['type'])?0:$_GET['type'];
$id = empty($_GET['id'])?0:intval($_GET['id']);
$picid = empty($_GET['picid'])?0:intval($_GET['picid']);
$page = empty($_GET['page'])?1:intval($_GET['page']);
if(empty($_GET['goto'])) $_GET['goto'] = '';
if($page<1) $page=1;

if (($type!='spot') && ($type!='profile'))
    showmessage('error_404');

if ($_GET['op'] == 'add') {
    if (!submitcheck('spotsubmit')) {
        ob_start();
        include_once template('site/tpl/add_prof_onpic');
        $bgcontent = ob_get_contents();
        ob_end_clean();

        $r['html']=$bgcontent;
        echo json_encode($r);
        exit;
    } else {
        $r['err'] = $r['step'] = 0;
        $profile_name =  empty($_POST['profile_name'])?'':trim($_POST['profile_name']);
        
        if(strlen($profile_name) < 2) {
            $r['err'] = "档案名不能小于1个中文字(2个英文字符)";
            echo json_encode($r);
            exit;
        }

        if(strlen($profile_name) > 50) {
            $r['err'] = "档案名不能多于25个中文字(50个英文字符)";
            echo json_encode($r);
            exit;
        }

        $query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('mtag')." WHERE tagname='$profile_name'");
        if($mtag = $_SGLOBAL['db']->fetch_array($query)) {
            if ($mtag['tagtype']) {
                //判断是否存在
                $tagid = $mtag['tagid'];

                $arr = array();
                $query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('mtag')." WHERE tagid='$id' AND tagtype='1'");
                if(!$mtag2 = $_SGLOBAL['db']->fetch_array($query)) {
                    //
                    $r['err'] = "不存在该档案";
                    echo json_encode($r);
                    exit;
                }

                $query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('profpic')." WHERE profid='$tagid' AND picid='$picid'");
                if(!$exists = $_SGLOBAL['db']->fetch_array($query)) {
                    //
                    $psetarr = array(
                                     'picid' => $picid,
                                     'profid' => $tagid,
                                     'uid' => $_SGLOBAL['supe_uid'],
                                     'dateline' => $_SGLOBAL['timestamp'],
                                     'postip' => getonlineip()
                                    );
                    inserttable('profpic', $psetarr, 1);
                    echo json_encode($r);
                    exit;
                } else {
                    $r['err'] = "该档案已经存在";
                    echo json_encode($r);
                    exit;
                }
            }
        } else {
            // FIXME: not exist, then let user create a profile now
            //
            $r['err'] = $r['step'] = 1;
            ob_start();
            $cateselect = '<option value=0>   </option>\n';
            $subcatselect = "case \"0\":\n";
            $subcatselect .= "var sfOptions = new Array(";
            $subcatselect .= "\t\"\", \"0\");";
            $subcatselect .= "\t break;";
            $sfid = 0;
            $picreferred = 1;
            $pageid = $p;
            if (!isset($fid)) {
                foreach ($_SGLOBAL['profield'] as $p) {
                    if (!$p['parentid'] && $p['profieldtype']) {
                        $cateselect .= "<option value=\"".$p[fieldid]."\">".$p[title]."</option>\n"; 
                        $subcatselect.= "case \"".$p[fieldid]."\":\n";
                        $subcatselect.= "var sfOptions = new Array(";
                        $subcatselect.= "\" \", \"0\",\n";
                        foreach ($_SGLOBAL['profield'] as $k) {
                            if ($k['parentid'] == $p['fieldid']) {
                                $subcatselect .= "\"".$k['title']."\", \"".$k['fieldid']."\",\n"; 
                            }
                        }
                        $subcatselect = substr($subcatselect,0,-2) ."\t);\n";
                        $subcatselect .= "\tbreak;\n";
                    }
                }
            }
            include_once template('site/tpl/create_profile');
            $bgcontent = ob_get_contents();
            ob_end_clean();

            $r['html']=$bgcontent;
            echo json_encode($r);
            exit;
        }

        $r['err'] = 'oops';
        echo json_encode($r);
        exit;

        if (!isset($tagid))
            return;
    } 
} else if ($_GET['op'] == 'editpic') {
    $r['err'] = 0;
    foreach ($_POST['title'] as $picid => $value) {
        $title = getstr($value, 150, 1, 1, 1);
        updatetable('pic', array('title'=>$title), array('picid'=>$picid, 'uid'=>$_SGLOBAL['supe_uid']));
    }
    $r['pic_title'] = $title;
    echo json_encode($r);
    exit; 
} else if ($_GET['op'] == 'list') {
    //图片列表
    $perpage = 20;
    $start = ($page-1)*$perpage;

    //检查开始数
    ckstart($start, $perpage);

	//图片列表
	$list = array();

    //查询相册
    if($id > 0) {
        if ($type == 'spot') {
			$count = getspotpiccnt($id);
			if ($count) {
                $sql = "SELECT DISTINCT p.* FROM ".tname('profpic')." pp, ".tname('pic')." p WHERE p.picid=pp.picid AND pp.profid IN (SELECT tag1 FROM ".tname('spot')." WHERE spotid=".$id.") AND pp.picid IN (SELECT picid FROM ".tname('profpic')." WHERE profid IN (SELECT tag2 FROM ".tname('spot')." WHERE spotid=".$id.")) ORDER BY p.dateline DESC LIMIT $start, $perpage";
                $query = $_SGLOBAL['db']->query($sql);
                while ($value = $_SGLOBAL['db']->fetch_array($query)) {
					$value['pic'] = mkpicurl($value);
					$value['p'] = $start + $i;
					$list[] = $value;
					$i++;
				}
            }
        } else {
            $sql = "SELECT count(*) FROM (SELECT DISTINCT * FROM ".tname('profpic')." WHERE profid ='$id') AS cnt";
            $count = $_SGLOBAL['db']->result($_SGLOBAL['db']->query($sql), 0);
            $wheresql = "pp.profid='$id'";

			if($count) {
				$query = $_SGLOBAL['db']->query("SELECT DISTINCT p.* FROM ".tname('pic')." p, ".tname('profpic')." pp WHERE p.picid=pp.picid AND $wheresql ORDER BY dateline DESC LIMIT $start,$perpage");
				while ($value = $_SGLOBAL['db']->fetch_array($query)) {
					$value['pic'] = mkpicurl($value);
					$value['p'] = $start + $i;
					$list[] = $value;
					$i++;
				}
			}
        }
    } 
    
    //分页
    $multi = multi($count, $perpage, $page, "site.php?ac=image&op=list&type=$type&id=$id");

	if ($type == 'spot') {
		$p = empty($_GET['p'])?0:intval($_GET['p']); 
		if(empty($_GET['goto'])) $_GET['goto'] = '';

		$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('spot')." WHERE spotid=".$id);
		if (!($spot =$_SGLOBAL['db']->fetch_array($query)))
			showmessage('no_spot');

		// get the spot's 2 profile image.
		$spotpics = getspot2prof($id);
		$pcount = getspotpiccnt($id);

		$mtag = getmtag($spot[tag1]);
        if (!$mtag) showmessage('no_profile');

		$mtag1 = getmtag($spot[tag2]);
        if (!$mtag1) showmessage('no_profile');
		
		$nav_name = get_parent_name_by_fid($mtag['fieldid']);
		$li_name = get_li_name_by_fid($mtag['fieldid']);

		if (!$nav_name) {
			showmessage('error_404');
			exit;
		}

		$at_nav_cate = getprofieldtxtbyfid($mtag1['fieldid']); 
		if (!$at_nav_cate) {
			showmessage('error_404');
			exit;
		}

		include_once template("site/tpl/spot_piclist");
		exit;
	} elseif ($type == 'profile') {

		$page = empty($_GET['page'])?1:intval($_GET['page']);
		if($page<1) $page=1;
		$tagid = empty($_GET['id'])?0:intval($_GET['id']);
		
		//指定的群组
		$mtag = getmtag($tagid);
        if (!$mtag) showmessage('no_profile');

		
		$nav_name = get_parent_name_by_fid($mtag['fieldid']);
		$li_name = get_li_name_by_fid($mtag['fieldid']);

		if (!$nav_name) {
			showmessage('error_404');
			exit;
		}

        //群组首页
		$list2[] = $starlist = $modlist = $memberlist = $checklist = array();
		
		if ($mtag['allowview']) {
			//会员
			$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('tagspace')." WHERE tagid='$tagid' AND grade='0' LIMIT 0,12");
			while ($value = $_SGLOBAL['db']->fetch_array($query)) {
				realname_set($value['uid'], $value['username']);
				$memberlist[] = $value;
			}
		}
		//群主
		$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('tagspace')." WHERE tagid='$tagid' AND grade>'7' ORDER BY grade DESC LIMIT 0,12");
		while ($value = $_SGLOBAL['db']->fetch_array($query)) {
			realname_set($value['uid'], $value['username']);
			$modlist[] = $value;
		}
		
		realname_get();
		include_once template("site/tpl/profile_pic");
		exit;
	}
} else  {  // per pic status.
    if(empty($_GET['goto'])) $_GET['goto'] = '';

    if ($type == 'spot') {
		$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('spot')." WHERE spotid=".$id);
		if (!($spot =$_SGLOBAL['db']->fetch_array($query)))
			showmessage('no_spot');

		// get the spot's 2 profile image.
		$spotpics = getspot2prof($id);
		$pcount = getspotpiccnt($id);

		//指定的群组
		$mtag = getprof($spot['tag1']);
		if (!$mtag) showmessage('no_profile');

		$nav_name = get_parent_name_by_fid($mtag['fieldid']);
		$li_name = get_li_name_by_fid($mtag['fieldid']);

		if (!$nav_name) {
			showmessage('error_404');
			exit;
		}

		$mtag1 = getmtag($spot[tag2]);
        if (!$mtag1) showmessage('no_profile');
		
		$at_nav_cate = getprofieldtxtbyfid($mtag1['fieldid']); 
		if (!$at_nav_cate) {
			showmessage('error_404');
			exit;
		}

	} elseif ($type == 'profile') {
		$tagid = empty($_GET['id'])?0:intval($_GET['id']);

		//指定的群组
		$mtag = getprof($tagid);
        if (!$mtag) showmessage('no_profile');

		$nav_name = get_parent_name_by_fid($mtag['fieldid']);
		$li_name = get_li_name_by_fid($mtag['fieldid']);

		if (!$nav_name) {
			showmessage('error_404');
			exit;
		}

		//群组首页
		$list2[]=$starlist = $modlist = $memberlist = $checklist = array();
		
		//群主
		$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('tagspace')." WHERE tagid='$tagid' AND grade>'7' ORDER BY grade DESC LIMIT 0,12");
	
		realname_get();
	
		$sql = "SELECT count(*) FROM ".tname('profpic')." WHERE profid ='$id'";
        $pcount = $_SGLOBAL['db']->result($_SGLOBAL['db']->query($sql), 0);
	}
    
    if ($picid && $type == 'spot') {
        $sql = "SELECT p.* FROM ".tname('spot')." sp, ".tname('pic')." p LEFT JOIN ".tname('profpic')." pp ON p.picid =pp.picid WHERE p.picid='$picid' AND (pp.profid=sp.tag1 OR pp.profid=sp.tag2) AND sp.spotid =".$id;
        //单个图片
        //检索图片
        $query = $_SGLOBAL['db']->query($sql);
        $pic = $_SGLOBAL['db']->fetch_array($query);
        //图片不存在
        if(empty($pic)) {
            showmessage('view_images_do_not_exist');
        } 
    } else if ($picid && $type == 'profile') {
        $sql = "SELECT p.* FROM ".tname('profpic')." pp LEFT JOIN ".tname('pic')." p ON p.picid=pp.picid WHERE p.picid='$picid' AND pp.profid =".$id;
        //单个图片
        //检索图片
        $query = $_SGLOBAL['db']->query($sql);
        $pic = $_SGLOBAL['db']->fetch_array($query);
        //图片不存在
        if(empty($pic)) {
            showmessage('view_images_do_not_exist');
        } 
    } else {
       if ($type == 'spot') {
            $pic = getspotpics($id, 0);
       } else {
            $pic = getprofpics($id, 0);
       } 
    }

    $ct = $_GET['goto'];
	if($ct) {
		if('up'==$ct) {
		    if ($type == 'spot') {
                $pic = getspotpic($id, $picid, 1);
                if (!$pic) $pic = getspotpics($id, 0);
            }    
            else {
                $pic = getprofpic($id, $picid, 1);
                if (!$pic) $pic = getprofpics($id, 0);
            }
		}
		if('down'==$ct) {
            if ($type == 'spot') {
		        $pic = getspotpic($id, $picid, -1);	
                if (!$pic) $pic = getspotpics($id, $pcount);
            }
            else {
                $pic = getprofpic($id, $picid, -1);
                if (!$pic) $pic = getspotpics($id, $pcount);
            } 
		}
   	}
    
    $picid = $pic['picid'];
    //图片存在
	if ($pic) 
    {		
        $sequence = getpicseq($id, $picid, $type);
        $pprofs = getpicprofs($picid);
        //图片地址
        $pic['pic'] = mkpicurl($pic, 0);
        $pic['size'] = formatsize($pic['size']);

        //图片的EXIF信息
        $exifs = array();
        $allowexif = function_exists('exif_read_data');
        if(isset($_GET['exif']) && $allowexif) {
            include_once(S_ROOT.'./source/function_exif.php');
            $exifs = getexif($pic['pic']);
        }

        //图片评论
        $perpage = 50;
        $start = ($page-1)*$perpage;
        
        //检查开始数
        ckstart($start, $perpage);

        $cid = empty($_GET['cid'])?0:intval($_GET['cid']);
        $csql = $cid?"cid='$cid' AND":'';
        $siteurl = getsiteurl();
        $list = array();
        $idtype = $type == 'spot' ? 'spicid' : 'ppicid';
        $count = $_SGLOBAL['db']->result($_SGLOBAL['db']->query("SELECT COUNT(*) FROM ".tname('comment')." WHERE $csql id='$pic[picid]' AND idtype='".$idtype."'"),0);
        if($count) {
            $query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('comment')." WHERE $csql id='$pic[picid]' AND idtype='$idtype' ORDER BY dateline LIMIT $start,$perpage");
            while ($value = $_SGLOBAL['db']->fetch_array($query)) {
                realname_set($value['authorid'], $value['author']);
                $list[] = $value;
            }
        }

        //分页
        $multi = multi($count, $perpage, $page, "site.php?ac=image&type=$type&id=$id");

        //实名
        realname_get();

        //图片全路径
        $pic_url = $pic['pic'];
        if(!preg_match("/^http\:\/\/.+?/i", $pic['pic'])) {
            $pic_url = getsiteurl().$pic['pic'];
        }
        $pic_url2 = rawurlencode($pic['pic']);

        if ($type == 'spot')
            $title_nav = '时尚发现';
        else 
            $title_nav = '图片';

        $title_nav1 = $type == 'spot' ? $mtag1[tagname] : '';

   }

   include template("site/tpl/spot_view");
   exit; 
}

?>
